<template>
  <div class="tag-selector">
    <!-- 输入框容器 -->
    <div class="input-container">
      <el-input
        v-model="inputValue"
        placeholder="输入标签名称或选择现有标签..."
        @keyup.enter="addTag"
        @input="onInput"
        @focus="showSuggestions = true"
        @blur="hideSuggestions"
        clearable
        ref="inputRef"
      />
      
      <!-- 下拉建议列表 -->
      <div class="suggestions-dropdown" v-if="showSuggestions && filteredSuggestions.length > 0">
        <div class="suggestion-item" 
             v-for="tag in filteredSuggestions" 
             :key="tag.id"
             @mousedown="selectTag(tag.id)"
             :class="{ 'selected': selectedTagIds.includes(tag.id) }">
          {{ tag.name }}
        </div>
        <div v-if="inputValue && !exactMatch" 
             class="suggestion-item create-new"
             @mousedown="addTag">
          创建新标签: "{{ inputValue }}"
        </div>
      </div>
    </div>
    
    <!-- 已选择的标签 -->
    <div class="selected-tags" v-if="selectedTagIds.length > 0">
      <div class="selected-tags-label">已选择的标签：</div>
      <div class="tag-list">
        <el-tag
          v-for="tagId in selectedTagIds"
          :key="`tag-${tagId}`"
          closable
          @close="removeTag(tagId)"
          class="selected-tag"
        >
          {{ getTagName(tagId) }}
        </el-tag>
      </div>
    </div>
    
    <!-- 推荐标签 -->
    <div class="tag-suggestions" v-if="availableTags.length > 0 && !showSuggestions">
      <div class="suggestion-label">推荐标签：</div>
      <div class="suggestion-tags">
        <el-tag
          v-for="tag in availableTags.slice(0, 8)"
          :key="tag.id"
          @click="selectTag(tag.id)"
          class="suggestion-tag"
          :class="{ 'selected': selectedTagIds.includes(tag.id) }"
        >
          {{ tag.name }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import type { Tag } from '@/types'

interface Props {
  modelValue: number[]
  availableTags: Tag[]
}

interface Emits {
  (e: 'update:modelValue', value: number[]): void
  (e: 'tag-created', tag: Tag): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const inputValue = ref('')
const showSuggestions = ref(false)
const inputRef = ref()

// 使用计算属性来避免递归更新
const selectedTagIds = computed({
  get: () => {
    if (!Array.isArray(props.modelValue)) {
      return []
    }
    return props.modelValue.filter(id => !isNaN(Number(id)))
  },
  set: (value: number[]) => {
    emit('update:modelValue', [...value])
  }
})

// 过滤建议标签
const filteredSuggestions = computed(() => {
  if (!inputValue.value.trim()) {
    return props.availableTags.slice(0, 10)
  }
  
  const query = inputValue.value.toLowerCase()
  return props.availableTags.filter(tag => 
    tag.name.toLowerCase().includes(query) &&
    !selectedTagIds.value.includes(tag.id)
  ).slice(0, 10)
})

// 检查是否有精确匹配
const exactMatch = computed(() => {
  if (!inputValue.value.trim()) return false
  return props.availableTags.some(tag => 
    tag.name.toLowerCase() === inputValue.value.toLowerCase()
  )
})

// 获取标签名称
const getTagName = (tagId: number) => {
  const tag = props.availableTags.find(t => t && t.id === tagId)
  return tag ? tag.name : `标签${tagId}`
}

// 创建新标签
const createNewTag = async (tagName: string) => {
  try {
    const response = await api.post('/posts/tags', {
      name: tagName,
      description: '',
      color: '#409EFF'
    })
    
    const newTag = response.data
    if (newTag && typeof newTag.id === 'number' && typeof newTag.name === 'string') {
      ElMessage.success(`标签 "${tagName}" 创建成功`)
      emit('tag-created', newTag)
      return newTag.id
    } else {
      throw new Error('创建的标签格式不正确')
    }
  } catch (error) {
    console.error('创建标签失败:', error)
    ElMessage.error('创建标签失败')
    throw error
  }
}

// 添加标签
const addTag = async () => {
  const tagName = inputValue.value.trim()
  if (!tagName) return
  
  // 查找现有标签
  const existingTag = props.availableTags.find(t => 
    t.name.toLowerCase() === tagName.toLowerCase()
  )
  
  if (existingTag) {
    selectTag(existingTag.id)
  } else {
    // 创建新标签
    try {
      const newTagId = await createNewTag(tagName)
      selectTag(newTagId)
    } catch (error) {
      console.error('创建标签失败:', error)
    }
  }
  
  inputValue.value = ''
  showSuggestions.value = false
}

// 选择标签
const selectTag = (tagId: number) => {
  const currentIds = selectedTagIds.value
  if (!currentIds.includes(tagId)) {
    selectedTagIds.value = [...currentIds, tagId]
  }
  inputValue.value = ''
  showSuggestions.value = false
}

// 移除标签
const removeTag = (tagId: number) => {
  const currentIds = selectedTagIds.value
  const index = currentIds.indexOf(tagId)
  if (index > -1) {
    const newIds = [...currentIds]
    newIds.splice(index, 1)
    selectedTagIds.value = newIds
  }
}

// 输入处理
const onInput = (value: string) => {
  showSuggestions.value = true
}

// 隐藏建议列表
const hideSuggestions = () => {
  // 延迟隐藏，让点击事件先触发
  setTimeout(() => {
    showSuggestions.value = false
  }, 200)
}
</script>

<style scoped>
.tag-selector {
  width: 100%;
  position: relative;
}

.input-container {
  position: relative;
}

.suggestions-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
}

.suggestion-item {
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  border-bottom: 1px solid #f5f7fa;
  transition: all 0.2s ease;
}

.suggestion-item:hover {
  background: #f5f7fa;
  color: #409eff;
}

.suggestion-item.selected {
  background: #e6f7ff;
  color: #409eff;
}

.suggestion-item.create-new {
  background: #f0f9ff;
  color: #0369a1;
  font-weight: 500;
  border-top: 1px solid #e0f2fe;
}

.suggestion-item.create-new:hover {
  background: #e0f2fe;
}

.selected-tags {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.selected-tags-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.selected-tag {
  margin: 0;
  transition: all 0.2s ease;
  background: #e6f7ff !important;
  border: 1px solid #91d5ff !important;
  color: #1890ff !important;
  font-weight: 500;
  font-size: 13px;
  padding: 4px 12px !important;
}

.selected-tag:hover {
  background: #bae7ff !important;
  border-color: #69c0ff !important;
}

.tag-suggestions {
  margin-top: 12px;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #e0f2fe;
}

.suggestion-label {
  font-size: 12px;
  color: #0369a1;
  margin-bottom: 8px;
  font-weight: 500;
}

.suggestion-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.suggestion-tag {
  cursor: pointer;
  transition: all 0.2s ease;
  margin: 0;
  background: transparent !important;
  border: 1px solid #d0d7de !important;
  color: #333 !important;
  font-weight: 500;
}

.suggestion-tag:hover {
  transform: scale(1.05);
  border-color: #409eff !important;
  background: #f0f9ff !important;
  color: #409eff !important;
}

.suggestion-tag.selected {
  border-color: #409eff !important;
  background: #e6f7ff !important;
  color: #409eff !important;
}
</style>
